import os
from urllib.parse import quote_plus

from dotenv import load_dotenv
from pymongo import MongoClient

load_dotenv()


# ------------------------
# MonGoDB 基础配置
# ------------------------
MONGODB_DEFAULTS = {
    'MonGoDB_USERNAME': 'admin',
    'MonGoDB_PASSWORD': '',
    'MonGoDB_HOST': 'localhost',
    'MonGoDB_PORT': '27017',
    'MonGoDB_DATABASE': '',
    'MonGoDB_AUTH_SOURCE': '',
    'MonGoDB_REPLICA_SET': '',
    'MONGO_URI_SCHEME': 'mongodb',
    'MONGO_CONNECT_TIMEOUT_MS': '5000',
    'MONGO_SOCKET_TIMEOUT_MS': '30000',
    'MONGO_MAX_POOL_SIZE': '100',
    'MONGO_MIN_POOL_SIZE': '10',
    'MONGO_MAX_IDLE_TIME_MS': '600000',
    'MONGO_SSL': 'False',
    'MONGO_SSL_CA_FILE': '',
    'CONSOLE_API_URL': '',
    'CHECK_UPDATE_URL': '',
    'DEPLOY_ENV': 'PRODUCTION',
    'LOG_LEVEL': 'INFO',
    'LOG_FILE': '',
    'LOG_FORMAT': '%(asctime)s.%(msecs)03d %(levelname)s [%(threadName)s] [%(filename)s:%(lineno)d] - %(message)s',
    'LOG_DATEFORMAT': '%Y-%m-%d %H:%M:%S',
}

def get_mongodb_env(key):
    return os.environ.get(key, MONGODB_DEFAULTS.get(key))

class MonGoDBBuilder:
    """
    创建 MonGoDB 连接
    """

    @staticmethod
    def get_mongo_client():
        username = quote_plus(get_mongodb_env('MonGoDB_USERNAME'))
        password = quote_plus(get_mongodb_env('MonGoDB_PASSWORD'))

        if username == "" or password == "":
            return MongoClient(
                host=f"{get_mongodb_env('MONGO_URI_SCHEME')}://"
                     f"{get_mongodb_env('MonGoDB_HOST')}:{get_mongodb_env('MonGoDB_PORT')}/"
            )

        return MongoClient(
            host=f"{get_mongodb_env('MONGO_URI_SCHEME')}://{username}:{password}@"
                 f"{get_mongodb_env('MonGoDB_HOST')}:{get_mongodb_env('MonGoDB_PORT')}/"
        )

